package org.joyflow.core.service;

import lombok.RequiredArgsConstructor;
import org.joyflow.core.entity.Db;
import org.joyflow.core.entity.DbConType;
import org.joyflow.core.entity.DbDir;
import org.joyflow.core.entity.DbType;
import org.joyflow.core.instance.DbFactory;
import org.joyflow.core.mapper.DbConTypeMapper;
import org.joyflow.core.mapper.DbDirMapper;
import org.joyflow.core.mapper.DbMapper;
import org.joyflow.core.mapper.DbTypeMapper;
import org.joyflow.core.meta.Database;
import org.joyflow.core.meta.DbMeta;
import org.joyflow.core.meta.DbMetaCodes;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

@Service
@RequiredArgsConstructor
public class SpringDbService implements DbServiceInterface {
    private final DbTypeMapper dbTypeMapper;
    private final DbConTypeMapper dbConTypeMapper;
    private final DbDirMapper dbDirMapper;
    private final DbMapper dbMapper;
    @Override
    public List<DbType> getDatabaseTypes() {
        return dbTypeMapper.selectList(null);
    }

    @Override
    public List<DbConType> getDatabaseConTypes() {
        return dbConTypeMapper.selectList(null);
    }

    @Override
    public List<DbDir> getDirs() {
        return dbDirMapper.selectList(null);
    }

    @Override
    public void insertDir(DbDir dir) {
        dbDirMapper.insert(dir);
    }

    @Override
    public void deleteDir(Serializable id) {
        dbDirMapper.deleteById(id);
    }

    @Override
    public void renameDir(DbDir dir) {
        dbDirMapper.updateById(dir);
    }

    @Override
    public DbDir getDir(Serializable id) {
        return dbDirMapper.selectById(id);
    }

    @Override
    public List<Db> getDbs() {
        return dbMapper.selectList(null);
    }

    @Override
    public Object test(Db db) {
        DbMeta dbMeta = DbMetaCodes.decode(db);
        return DbFactory.instance().test(dbMeta);
    }

    @Override
    public Db getDb(Serializable id) {
        return dbMapper.selectById(id);
    }

    @Override
    public Object execStatement(Long dbId, String statement) {
        Db db = getDb(dbId);
        DbMeta dbMeta = DbMetaCodes.decode(db);
        Database database = new Database(dbMeta);
        database.execStatements(List.of(statement));
        return true;
    }
}
